package juc;

/**
 * 同步锁与volatile
 * synchronized 具有互斥性
 * volatile不具备互斥性,不具备原子性
 */
public class TestVolatile {
    public static void main(String[] args) {
        ThreadDemo td = new ThreadDemo();
        new Thread(td).start();
        while (true) {
            if (td.isFlag()) {
                System.out.println("------");
                break;
            }
        }
        //性能低下
        while (true) {
            synchronized (td) {
                if (td.isFlag()) {
                    System.out.println("------");
                    break;
                }
            }
        }
    }
}

class ThreadDemo implements Runnable {

    //    private boolean flag = false;
    private volatile boolean flag = false;

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = true;
        System.out.println("flag=" + isFlag());
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
